package by.wind.drebedengi.asynctask;

import java.util.ArrayList;

import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;

import by.wind.drebedengi.R;
import by.wind.drebedengi.database.MyDatabaseHelper;
import by.wind.drebedengi.datalayer.SetRecordElementResult;
import by.wind.drebedengi.datalayer.SetRecordList;
import by.wind.drebedengi.datalayer.bean.Record;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class UploadAsyncTask extends AbstractTask {

	public UploadAsyncTask(Context aContext) {
		super(aContext);
		itsProgressMessage = itsContext.getString(R.string.task_saving);
	}

	@Override
	public void setProgressTracker(IProgressTracker progressTracker) {
		// Attach to progress tracker
		itsProgressTracker = progressTracker;
		// Initialize progress tracker with current task state
		if (itsProgressTracker != null) {
			itsProgressTracker.onProgress(itsProgressMessage);
			if (itsResult != null) {
				itsProgressTracker.onComplete();
			}
		}
	}

	@Override
	protected int getProgressType() {
		return ProgressDialog.STYLE_SPINNER;
	}

	@Override
	protected Boolean doInBackground(Long... params) {
		if (!isNetworkAvailable()) {
			// throw new
			// Exception(itsContext.getString(R.string.connection_error));
			return false;
		}
		MyDatabaseHelper itsHelper = new MyDatabaseHelper(itsContext);
		try {
			RuntimeExceptionDao<Record, Integer> dao = itsHelper
					.getRecordDataDao();
			QueryBuilder<Record, Integer> qb = dao.queryBuilder();
			PreparedQuery<Record> preparedQuery = qb.where()
					.eq(Record.SERVER_ID, 0).prepare();
			ArrayList<Record> recordList = (ArrayList<Record>) dao
					.query(preparedQuery);
			SetRecordList itsSetRecordList = new SetRecordList(recordList);
			itsSetRecordList.loadData();
			ArrayList<SetRecordElementResult> recordListResult = itsSetRecordList
					.getSetRecordListResult();
			for (Record element : recordList) {
				for (SetRecordElementResult resultElement : recordListResult) {
					if (resultElement.getClient_id() == element.getClient_id()
							&& resultElement.getStatus().equals(
									SetRecordElementResult.INSERTED)) {
						element.setServer_id(resultElement.getServer_id());
						break;
					}
				}
			}
			itsHelper.updateRecordList(recordList);
		} catch (Exception ex) {
			ex.printStackTrace();
			return false;
		} finally {
			itsHelper.close();
		}
		return true;
	}

	@Override
	public String onErrorMessage() {
		return itsContext.getString(R.string.task_upload_error);
	}

}
